package znet

import (
	"errors"
	"fmt"
	"sync"
	"zinx/ziface"
)

/*
*
链接管理模块
*/
type ConnManager struct {
	connections map[uint32]ziface.IConnection //链接集合

	connLock sync.RWMutex // 保护链接集合的读写锁

}

// 创建当前链接的方法
func NewConnManager() *ConnManager {
	return &ConnManager{
		connections: make(map[uint32]ziface.IConnection),
	}
}

// 添加链接
func (connManager *ConnManager) Add(conn ziface.IConnection) {
	// 保护共享资源map ,加写锁
	connManager.connLock.Lock()
	defer connManager.connLock.Unlock()

	//将conn加入到ConnManager中
	connManager.connections[conn.GetConnID()] = conn
	fmt.Println("connID = ", conn.GetConnID(), "connection add to ConnManager successfully : conn num =", connManager.Len())
}

// 删除链接
func (connManager *ConnManager) Remove(conn ziface.IConnection) {
	// 保护共享资源map ,加写锁
	connManager.connLock.Lock()
	defer connManager.connLock.Unlock()

	//删除链接信息
	delete(connManager.connections, conn.GetConnID())
	fmt.Println("connID = ", conn.GetConnID(), "connection remove to ConnManager successfully : conn num =", connManager.Len())

}

// 根据connID获取链接
func (connManager *ConnManager) Get(connID uint32) (ziface.IConnection, error) {
	// 保护共享资源map ,加读锁
	connManager.connLock.RLock()
	defer connManager.connLock.RLocker()

	if conn, ok := connManager.connections[connID]; ok {
		//找到了对应链接
		return conn, nil
	} else {
		return nil, errors.New("connction not found!")
	}
}

// 得到当前链接总数
func (connManager *ConnManager) Len() int {
	return len(connManager.connections)
}

// 清除并终止所有的链接
func (connManager *ConnManager) ClearConn() {
	// 保护共享资源map ,加写锁
	connManager.connLock.Lock()
	defer connManager.connLock.Unlock()

	// 删除conn 并停止conn的工作
	for connID, conn := range connManager.connections {
		// 停止
		conn.Stop()
		//删除
		delete(connManager.connections, connID)
		fmt.Println("Clear All connection succ! conn num=", connManager.Len())
	}
}
